package com.fzx.fzwsupplysystem.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import java.io.File;
import java.util.Map;
import java.util.Set;
/*
 * 使用说明：
 * 1.SharePreferenceUtil spUtil = SharePreferenceUtil.getInstance(context);
 * 2.spUtil.putStringValue("","");
 * 3.spUtil.getStringValue("","");
 * 4.每一次提交数据都需要执行spUtil.apply()或者spUtil.commit();
 * 5.spUtil.setSharePreference("","");设置保存的文件名和模式
 * 6.spUtil.setDefault();设置默认保存的文件名和模式
 * 7.可以使用链式调用
 * 8.示例：SharePreferenceUtil.getInstance(context).putStringValue("","").putStringValue("","").apply();
 */

/**
 * 描述：    SharePreference数据存储工具类
 * 项目名称：AndroidUtilsDemo
 * 创建人：  FangZhixin
 * 创建时间：2018/7/6
 */
public class SharePreferenceUtil {

    private static final String TAG = "SharePreferenceUtil";

    private static final String defaultName = "SharePreferenceUtil";
    private static final int defaultMode = Context.MODE_PRIVATE;
    private String mSharePreferenceName;
    private int mMode;
    private static SharedPreferences sp;
    private static SharedPreferences.Editor editor;

    @SuppressLint("StaticFieldLeak")
    private static SharePreferenceUtil sharePreferenceUtil;

    private Context mContext;

    private SharePreferenceUtil() {

    }

    /**
     * 初始化构造
     *
     * @param context 上下文
     */
    @SuppressLint("CommitPrefEdits")
    private SharePreferenceUtil(Context context) {
        /*if (!(context instanceof Application)) {
            mContext = context.getApplicationContext();
        } else {
        }*/
        mContext = context;
        setDefault();
    }

    /**
     * 单例模式
     *
     * @param context 上下文，最好用全局的getApplicationContext()
     * @return 本类对象SharePreferenceUtil
     */
    public static SharePreferenceUtil getInstance(Context context) {
        Log.i(TAG, "getInstance: sharePreferenceUtil=" + sharePreferenceUtil);
        if (sharePreferenceUtil == null) {
            synchronized (SharePreferenceUtil.class) {
                if (sharePreferenceUtil == null) {
                    sharePreferenceUtil = new SharePreferenceUtil(context);
                }
            }
        }
        return sharePreferenceUtil;
    }

    /**
     * 一开始初始化默认调用，当调用了设置自定义的方法时，下次使用默认需要重定义
     */
    @SuppressLint("CommitPrefEdits")
    public void setDefault() {
        mSharePreferenceName = defaultName;
        mMode = defaultMode;
        sp = mContext.getSharedPreferences(defaultName, defaultMode);
        editor = sp.edit();
    }

    /**
     * 自定义SharedPreferences的文件名和模式
     *
     * @param spName 保存的文件名，不包含后缀
     * @param mode   保存的模式，Context.MODE_PRIVATE，MODE_WORLD_READABLE，MODE_WORLD_WRITEABLE
     */
    @SuppressLint("CommitPrefEdits")
    public void setSharePreference(String spName, int mode) {
        mSharePreferenceName = spName;
        mMode = mode;
        sp = mContext.getSharedPreferences(mSharePreferenceName, mMode);
        editor = sp.edit();
    }

    public SharedPreferences getSharePreference() {
        return sp;
    }

    public SharedPreferences.Editor getEditor() {
        return editor;
    }

    public String getSharePreferenceName() {
        return mSharePreferenceName;
    }

    public int getMode() {
        return mMode;
    }

    public String getDefaultName() {
        return defaultName;
    }

    public int getDefaultMode() {
        return defaultMode;
    }

    public SharePreferenceUtil putStringValue(String name, String value) {
        editor.putString(name, value);
        return sharePreferenceUtil;
    }

    public SharePreferenceUtil putBooleanValue(String name, boolean value) {
        editor.putBoolean(name, value);
        return sharePreferenceUtil;
    }

    public SharePreferenceUtil putIntValue(String name, int value) {
        editor.putInt(name, value);
        return sharePreferenceUtil;
    }

    public SharePreferenceUtil putFloatValue(String name, Float value) {
        editor.putFloat(name, value);
        return sharePreferenceUtil;
    }

    public SharePreferenceUtil putLongValue(String name, Long value) {
        editor.putLong(name, value);
        return sharePreferenceUtil;
    }

    public SharePreferenceUtil putStringSet(String name, Set<String> values) {
        editor.putStringSet(name, values);
        return sharePreferenceUtil;
    }

    public String getStringValue(String name, String defaultValue) {
        return sp.getString(name, defaultValue);
    }

    public boolean getBooleanValue(String name, boolean defaultValue) {
        return sp.getBoolean(name, defaultValue);
    }

    public int getIntValue(String name, int defaultValue) {
        return sp.getInt(name, defaultValue);
    }

    public float getFloatValue(String name, float defaultValue) {
        return sp.getFloat(name, defaultValue);
    }

    public Long getLongValue(String name, long defaultValue) {
        return sp.getLong(name, defaultValue);
    }

    public Map<String, ?> getAll() {
        return sp.getAll();
    }

    /**
     * 获取Set<String>集合
     *
     * @param key String，Set<String>的key值
     * @param set Set<String>，这里最好直接 new HashSet<String>，如果传null的话，保存数据前都需要先清除xml中的对于key的set集合，否则存储数据可能会失败
     * @return Set<String>
     */
    public Set<String> getStringSet(String key, Set<String> set) {
        return sp.getStringSet(key, set);
    }

    public SharePreferenceUtil put(String key, Object object) {
        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            editor.putString(key, object.toString());
        }
        return sharePreferenceUtil;
    }

    public Object get(String key, Object defaultObject) {
        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        }
        return null;
    }

    /**
     * 是否包含该key
     *
     * @param key 保存的key值
     * @return boolean
     */
    public boolean contain(String key) {
        return sp.contains(key);
    }

    /**
     * 异步提交数据，更加高效，但是没有返回值
     */
    public void apply() {
        if (editor == null) {
            editor = sp.edit();
        }
        editor.apply();
    }

    /**
     * 同步提交数据，有提交数据成功的返回值
     *
     * @return boolean
     */
    public boolean commit() {
        if (editor == null) {
            editor = sp.edit();
        }
        return editor.commit();
    }

    /**
     * 移除当前文件下的对应key的数据
     *
     * @param key map集合中的key值
     * @return sharePreferenceUtil
     */
    public SharePreferenceUtil removeValue(String... key) {
        for (String aKey : key) {
            editor.remove(aKey);
        }
        return sharePreferenceUtil;
    }

    /**
     * 移除指定文件下的对应key的数据
     *
     * @param spName 文件名
     * @param mode   模式
     * @param key    map集合中的key值
     * @return sharePreferenceUtil
     */
    public SharePreferenceUtil removeValue(String spName, int mode, String... key) {
        SharedPreferences preferences = mContext.getSharedPreferences(mSharePreferenceName, mode);
        @SuppressLint("CommitPrefEdits")
        SharedPreferences.Editor editor = preferences.edit();
        for (String aKey : key) {
            editor.remove(aKey);
        }
        return sharePreferenceUtil;
    }

    /**
     * 清除当前文件里的所有数据
     *
     * @return boolean 是否清除成功
     */
    @SuppressLint("CommitPrefEdits")
    public SharePreferenceUtil clearData() {
        if (sp == null) {
            sp = mContext.getSharedPreferences(mSharePreferenceName, mMode);
        }
        if (editor == null) {
            editor = sp.edit();
        }
        editor.clear();
        return sharePreferenceUtil;
    }

    /**
     * 清除指定文件里的所有数据
     *
     * @param spName 文件名
     * @param mode   模式
     * @return boolean 是否清除成功
     */
    @SuppressLint("CommitPrefEdits")
    public SharePreferenceUtil clearData(String spName, int mode) {
        SharedPreferences preferences = mContext.getSharedPreferences(mSharePreferenceName, mode);
        SharedPreferences.Editor editor = preferences.edit();
        editor.clear();
        return sharePreferenceUtil;
    }

    /**
     * 删除指定文件
     *
     * @param spName 文件名
     * @return boolean 是否删除成功
     */
    public boolean deleteFile(String spName) {
        File file = new File("/data/data/" + mContext.getPackageName() + "/shared_prefs", spName + ".xml");
        return file.exists() && file.delete();
    }

    public void release() {
        editor = null;
        sp = null;
        sharePreferenceUtil = null;
    }

}
